import React, {PropsWithChildren, useEffect, useState} from 'react'
import {Button, Card, DatePicker, Space} from "antd";
import {DateTimeFormatter, YearMonth} from "@js-joda/core";
import StatisticCard from "../StatisticCard";
import {
    getMarketStatistic,
    getMarketSoldEveryMonthStatistic,
    MarketStatisticResponse, MarketSoldEveryMonthStatisticResponse
} from "../../apis/MarketStatisticApi";
import {Line} from "@ant-design/charts";
import Exceljs from "exceljs";
import {saveWorkbookTo} from "../../utils/FileSaver";
import {observer} from "mobx-react-lite";
import dashboardPageStore from "../../store/DashboardPageStore";
import LoadableButton from "../LoadableButton";

export interface MarketStatisticTabPanelProps extends PropsWithChildren {
    id: number
}

/**
 * 总送货零售价、总成本、总销售额
 *
 * 送货单数量、月份数量
 * 商品过滤
 */
const MarketStatisticTabPanel: React.FC<MarketStatisticTabPanelProps> = ({id}) => {
    const [statisticStartYearMonth, setStatisticStartYearMonth] = useState<YearMonth>()
    const [statisticEndYearMonth, setStatisticEndYearMonth] = useState<YearMonth>()
    const [statisticBrandIds, setStatisticBrandIds] = useState<number[]>()

    const [statisticResponse, setStatisticResponse] = useState<MarketStatisticResponse>()
    useEffect(() => {
        getMarketStatistic(id, {
            startYearMonth: statisticStartYearMonth,
            endYearMonth: statisticEndYearMonth,
            brandIds: statisticBrandIds
        }).then(response => {
            setStatisticResponse(response.data)
        })
    }, [statisticStartYearMonth?.toJSON(), statisticEndYearMonth?.toJSON(), statisticBrandIds, id]);

    const [statisticSoldByMonthStartYearMonth, setStatisticSoldByMonthStartYearMonth] = useState<YearMonth>()
    const [statisticSoldByMonthEndYearMonth, setStatisticSoldByMonthEndYearMonth] = useState<YearMonth>()
    const [statisticSoldByMonthBrandIds, setStatisticSoldByMonthBrandIds] = useState<number[]>()
    const [statisticSoldByMonthResponse, setStatisticSoldByMonthResponse] = useState<MarketSoldEveryMonthStatisticResponse>()
    useEffect(() => {
        getMarketSoldEveryMonthStatistic(id, {
            startYearMonth: statisticSoldByMonthStartYearMonth,
            endYearMonth: statisticSoldByMonthEndYearMonth,
            brandIds: statisticSoldByMonthBrandIds,
        }).then(response => {
            setStatisticSoldByMonthResponse(response.data)
        })
    }, [statisticSoldByMonthStartYearMonth?.toJSON(), statisticSoldByMonthEndYearMonth?.toJSON(), statisticSoldByMonthBrandIds, id]);

    return <Space direction={"vertical"} size={"large"} style={{width: "100%"}}>
        <Card title={"统计"} extra={<Space>
            <DatePicker.MonthPicker placeholder={"起始月"} onChange={date => {
                setStatisticStartYearMonth(date ? YearMonth.of(date.year(), date.month()) : undefined)
            }}/>
            <DatePicker.MonthPicker placeholder={"结束月（包含）"} onChange={date => {
                setStatisticEndYearMonth(date ? YearMonth.of(date.year(), date.month()) : undefined)
            }}/>
        </Space>}>
            {statisticResponse ? <Space>
                <StatisticCard title={"送货单总零售价"} value={statisticResponse.totalPrice.toString()}/>
                <StatisticCard title={"送货单数量"} value={statisticResponse.deliveryOrderCount.toString()}/>
                <StatisticCard title={"总成本"} value={statisticResponse.totalCost.toString()}
                               tips={"总成本仅供参考，单品在统计范围内的成本的变化未计算在内"}/>
                <StatisticCard title={"总销售额"} value={statisticResponse.totalSoled.toString()}/>
            </Space> : undefined}
        </Card>
        <Card title={"销量"} extra={<Space>
            <LoadableButton disabled={(statisticSoldByMonthResponse?.yearMonthData?.length ?? 0) <= 0} onClick={async () => {
                let workbook = new Exceljs.Workbook();
                let worksheet = workbook.addWorksheet("Sheet 1");
                let formatter = DateTimeFormatter.ofPattern("yyyy年M月");
                worksheet.columns = statisticSoldByMonthResponse!!.yearMonthData.map(item => {
                    return {
                        header: item.statisticYearMonth.format(formatter),
                        key: item.statisticYearMonth.toJSON(),
                    }
                })
                worksheet.addRow(statisticSoldByMonthResponse!.yearMonthData.map(item => item.totalSoled))
                let firstYearMonthString = statisticSoldByMonthResponse!.yearMonthData[0].statisticYearMonth.format(formatter);
                const rangeString = statisticSoldByMonthResponse!.yearMonthData.length > 1 ? `${firstYearMonthString}至${statisticSoldByMonthResponse!.yearMonthData[statisticSoldByMonthResponse!.yearMonthData.length - 1].statisticYearMonth.format(formatter)}` : firstYearMonthString
                return saveWorkbookTo(workbook, `${dashboardPageStore.currentPageTitle ?? "卖场"}${rangeString}月销售统计表`)
            }}>导出</LoadableButton>
            <DatePicker.MonthPicker placeholder={"起始月"} onChange={date => {
                setStatisticSoldByMonthStartYearMonth(date ? YearMonth.of(date.year(), date.month()) : undefined)
            }}/>
            <DatePicker.MonthPicker placeholder={"结束月（包含）"} onChange={date => {
                setStatisticSoldByMonthEndYearMonth(date ? YearMonth.of(date.year(), date.month()) : undefined)
            }}/>
        </Space>}>
            {!!statisticSoldByMonthResponse && <Line title={"月销售额趋势图"}
                                                     data={statisticSoldByMonthResponse.yearMonthData.map((it, index, array) => ({
                                                         label: array.findIndex(item => item.statisticYearMonth.year() === it.statisticYearMonth.year()) === index ? `${it.statisticYearMonth.year()}年${it.statisticYearMonth.monthValue()}月` : `${it.statisticYearMonth.monthValue()}月`,
                                                         value: it.totalSoled,
                                                         yearMonth: it.statisticYearMonth,
                                                     }))} xField={"label"} yField={"value"} axis={{
                x: {
                    title: "月份"
                },
                y: {
                    title: "月销售额",

                }
            }} tooltip={{
                title: i => i.yearMonth.format(DateTimeFormatter.ofPattern("yyyy年MM月")), items: [
                    {
                        name: "月销售额",
                        field: "value"
                    }
                ]
            }}
            />}
        </Card>
    </Space>
}

export default observer(MarketStatisticTabPanel)


